package com.coder.baseapp.mvp.presenter;

import com.coder.baseapp.mvp.base.BasePresenter;
import com.coder.baseapp.mvp.contract.LoginContract;
import com.coder.baseapp.mvp.model.entity.User;
import com.coder.baseapp.mvp.model.entity.def.ResponseEntity;
import com.coder.baseapp.wrapper.RxManager;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @Author: Tua.CoderGui
 * *
 * @Date: 2017/3/9
 * *
 * Copyright (c) 2017 All Rights Reserved.
 */

public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {

    private static final String TAG = "LoginPresenter";

    @Inject
    public LoginPresenter() {

    }

    @Override
    public void login(String username, String password) {

        mApi.login(username, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseEntity<User>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        mRxManager.add(s);
                        mView.showLoading(true);

                        //预备工作，在调用request之前做完
                        s.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onNext(ResponseEntity<User> responseEntity) {
                        mView.showSuccess();
                    }

                    @Override
                    public void onError(Throwable t) {
                        onComplete();
                        mView.showError(t.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        mView.showLoading(false);
                    }
                });
    }
}
